package com.tuyue.police.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @Author: 王金海
 * @Description: 日志拦截器
 * @Date: Created by Administrator on 2017/11/29.
 * @Modified By:
 */
@Aspect///*AOP
@Component//扫描
public class LogAspect {
    private final Logger logger= LoggerFactory.getLogger(this.getClass());
    @Pointcut("execution(* com.tuyue.police.controller.*.*.*(..))")
    public void log(){}

    @Before("log()")
    public void doBefore(JoinPoint joinPoint){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String url=request.getRequestURL().toString();
        String ip=request.getRemoteAddr();
        String method = request.getMethod();
        String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        RequestLog requestLog = new RequestLog(url, ip, method, classMethod, args);
        logger.info("【请求】：{}",requestLog.toString());
    }
    @After("log()")
    public void doAfter(){
        logger.info("【请求之后】");
    }

    @AfterReturning(returning = "o",pointcut = "log()")
    public void doAfterReturning(Object o){
        logger.info("【返回】:{}",o);
    }

    private class RequestLog{
        private String url;
        private String ip;
        private String type;
        private String classMethod;
        private Object[] args;

        @Override
        public String toString() {
            return "RequestLog{\n" +
                    " url='" + url + '\'' +
                    ",\n ip='" + ip + '\'' +
                    ",\n type='" + type + '\'' +
                    ",\n classMethod='" + classMethod + '\'' +
                    ",\n args=" + Arrays.toString(args) +
                    '}';
        }

        public RequestLog(String url, String ip, String type, String classMethod, Object[] args) {
            this.url = url;
            this.ip = ip;
            this.type = type;
            this.classMethod = classMethod;
            this.args = args;
        }
    }
}
